/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.HashMap;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.community.FriendsterLoginTask;
import com.mol.market.community.FriendsterLoginTask.FriendsterUser;

/**
 * 登录页
 * 
 * @author Andrew
 * @date 2011-5-25
 * 
 */
public class FriendsterLoginActivity extends BaseActivity implements
		OnClickListener, OnFocusChangeListener, ApiRequestListener {

	// private static final String TAG = "LoginActivity";

	private static final int DIALOG_PROGRESS = 0;

	// 用户不存在（用户名错误）
	private static final int ERROR_CODE_USERNAME_NOT_EXIST = 211;
	// 用户密码错误
	private static final int ERROR_CODE_PASSWORD_INVALID = 212;

	private EditText etUsername;

	private EditText etPassword;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_friendster_login_layout);
		initView();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		etUsername = null;
		etPassword = null;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(Activity.RESULT_CANCELED);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initView() {

		// top bar
		TopBar.createTopBar(mSession, this,
				new View[] { findViewById(R.id.top_bar_title) },
				new int[] { View.VISIBLE }, getString(R.string.login));

		etUsername = (EditText) findViewById(R.id.et_username);
		if ("1".equals(mSession.getLoginType())) {
			String userName = TextUtils.isEmpty(mSession.getUserName()) ? ""
					: mSession.getUserName();
			etUsername.setText(userName);
			if (!TextUtils.isEmpty(userName)) {
				etPassword.requestFocus();
			}
		}
		etUsername.setOnFocusChangeListener(this);
		etUsername.requestFocus();
		etPassword = (EditText) findViewById(R.id.et_password);
		etPassword.setOnFocusChangeListener(this);


		Button btnLogin = (Button) findViewById(R.id.btn_login);
		btnLogin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			login();
			break;
		}
	}

	/*
	 * Do login process
	 */
	private void login() {

		// 检查用户输入
		if (!checkUserName(etUsername) || !checkPassword(etPassword)) {
			return;
		}

		if (!isFinishing()) {
			showDialog(DIALOG_PROGRESS);
		} else {
			// 如果当前页面已经关闭，不进行登录操作
			return;
		}
		String userName = etUsername.getText().toString();
		String password = etPassword.getText().toString();
		try {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
				// "friendsterstore@yahoo.com", "qwe123rty"
				new FriendsterLoginTask(getApplicationContext(), userName,
						password, this).execute();
			} else {
				new FriendsterLoginTask(getApplicationContext(), userName,
						password, this)
						.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Utils.trackEvent(getApplicationContext(), Constants.GROUP_9,
				Constants.LOGIN);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);

		if (dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_PROGRESS:
			ProgressDialog mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setMessage(getString(R.string.singin));
			return mProgressDialog;

		default:
			return super.onCreateDialog(id);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSuccess(int method, Object obj) {
		switch (method) {
		case FriendsterLoginTask.METHOD_GET_USER:
			FriendsterUser user = (FriendsterUser) obj;
			String username = user.userName;
			String thirduid = user.uid + "";
			mSession.setUid(thirduid);
			mSession.setUserName(username);
			MarketAPI.thirdLogin(getApplicationContext(), this, username, 2, thirduid);
			break;
		case MarketAPI.ACTION_THRID_LOGIN:
			HashMap<String, String> result = (HashMap<String, String>) obj;
			Utils.trackEvent(getApplicationContext(), Constants.GROUP_9,
					Constants.LOGIN_SUCCESS);
			mSession.setUid(result.get(Constants.KEY_USER_UID));
			mSession.setUserName(etUsername.getText().toString());
			// 同步用户购买记录
			MarketAPI.syncBuyLog(getApplicationContext(), this);
			break;

		case MarketAPI.ACTION_SYNC_BUYLOG:

			syncBuyLogOver(true);
			break;
		default:
			break;
		}
	}

	@Override
	public void onError(int method, int statusCode) {

		switch (method) {
		case MarketAPI.ACTION_THRID_LOGIN:
		case FriendsterLoginTask.METHOD_GET_USER:
			// 隐藏登录框
			try {
				dismissDialog(DIALOG_PROGRESS);
			} catch (IllegalArgumentException e) {
			}

			String msg = null;
			if (statusCode == ERROR_CODE_USERNAME_NOT_EXIST) {
				msg = getString(R.string.error_login_username);
			} else if (statusCode == ERROR_CODE_PASSWORD_INVALID) {
				msg = getString(R.string.error_login_password);
			} else {
				msg = getString(R.string.error_login_other);
			}
			Utils.makeEventToast(getApplicationContext(), msg, false);
			break;

		case MarketAPI.ACTION_SYNC_BUYLOG:

			// 同步购买记录失败
			syncBuyLogOver(false);
			break;

		default:
			break;
		}
	}

	/*
	 * 同步购买记录完成，无论成功或者失败，登录操作都结束。 登录状态中，下次开启应用的时候同步购买记录。
	 */
	private void syncBuyLogOver(boolean isSuccess) {

		mSession.setLogin(true);
		Utils.makeEventToast(getApplicationContext(),
				getString(R.string.login_success), false);
		setResult(Activity.RESULT_OK);
		try {
			dismissDialog(DIALOG_PROGRESS);
		} catch (IllegalArgumentException e) {
		}
		finish();
	}

	@Override
	public void onFocusChange(View v, boolean flag) {
		switch (v.getId()) {
		case R.id.et_username:

			if (!flag) {
				checkUserName(etUsername);
			}
			break;

		case R.id.et_password:

			if (!flag) {
				checkPassword(etPassword);
			}
			break;

		default:
			break;
		}
	}

	/*
	 * 检查用户名合法性 不能为空
	 */
	private boolean checkUserName(EditText input) {
		String name = input.getText().toString();
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(name.trim())) {
			etUsername.setError(getString(R.string.error_username_empty));
			return false;
		}
		input.setError(null);
		return true;
	}

	/*
	 * 检查用户密码合法性 不能为空
	 */
	private boolean checkPassword(EditText input) {
		String password = input.getText().toString();
		if (TextUtils.isEmpty(password) || TextUtils.isEmpty(password.trim())) {
			input.setError(getString(R.string.error_password_empty));
			return false;
		}
		input.setError(null);
		return true;
	}
}